/**
 *  Exprezoo Records
 *  Copyright (C) 2012 Sergio De Mattia
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package com.sdmdev.android.exprezoorecords.json.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sdmdev.android.exprezoorecords.R;
import com.sdmdev.android.exprezoorecords.R.string;
import com.sdmdev.android.exprezoorecords.utility.ApplicationProperties;
import com.sdmdev.android.exprezoorecords.utility.Networking;

public class SongActivity extends Activity {
	String track; 
	String title;
	String author; 
	ImageView locandinaBtn;
	private static final String TAG = "SongActivity";

	MediaPlayer mp;
	private String download;
	private String releasedate;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		track = getIntent().getStringExtra("track");
		title = getIntent().getStringExtra("title");
		author = getIntent().getStringExtra("author");
		releasedate = getIntent().getStringExtra("releasedate");
		download = getIntent().getStringExtra("download");
		Log.d(TAG,  track + title + author );
		if(Networking.isNetworkAvailable(SongActivity.this)){
			new BackgroundWorker().execute();	
		}else{
			setContentView(R.layout.songview);
			Toast.makeText(SongActivity.this, string.noconnection, Toast.LENGTH_LONG).show(); 
		}
	}	


	 public static Bitmap getBitmapFromURL(String src) {
	        try {
	            Log.e("src",src);
	            URL url = new URL(src);
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoInput(true);
	            connection.connect();
	            InputStream input = connection.getInputStream();
	            Bitmap myBitmap = BitmapFactory.decodeStream(input);
	            Log.e("Bitmap","returned");
	            return myBitmap;
	        } catch (IOException e) {
	            e.printStackTrace();
	            Log.e("Exception",e.getMessage());
	            return null;
	        }
	    }
	 
	 
	 
	 public void audioPlayer(String path, String fileName){
		    //set up MediaPlayer    
		    mp = new MediaPlayer();
		 
		    try {
		        mp.setDataSource(path+"/"+fileName);
		    } catch (IllegalArgumentException e) {
		        Log.e("Exception " + TAG,e.getMessage());			    
		    } catch (IllegalStateException e) {
		        Log.e("Exception " + TAG,e.getMessage());
		    } catch (IOException e) {
		        Log.e("Exception " + TAG,e.getMessage());
		    }
		    try {
		        mp.prepare();
		    } catch (IllegalStateException e) {
		        Log.e("Exception " + TAG,e.getMessage());
		    } catch (IOException e) {
		        Log.e("Exception " + TAG,e.getMessage());
		    }
		    mp.start();
		}
	 
	 
	 private class BackgroundWorker extends AsyncTask<Void, Void, Void>{

		 Drawable image;
		 ProgressDialog myProgressDialog;
			public Object fetch(String address) throws MalformedURLException,
		    IOException {
		        URL url = new URL(address);
		        Object content = url.getContent();
		        return content;
		    }   
			
		    public Drawable ImageOperations(BackgroundWorker backgroundWorker, String url) {
		        try {
		            InputStream is = (InputStream) this.fetch(url);
		            Drawable d = Drawable.createFromStream(is, "src");
		            return d;
		        } catch (MalformedURLException e) {
		            return null;
		        } catch (IOException e) {
		            return null;
		        }
		    }

	    @Override
	    protected void onPreExecute() {
	    	// TODO Auto-generated method stub
	    	super.onPreExecute();
	    	myProgressDialog = ProgressDialog.show(SongActivity.this, title, "loading...");

	    }
	    
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			publishProgress();
			image =ImageOperations(this, ApplicationProperties.IMG_DIR + "/" + track + ".png");

			audioPlayer(ApplicationProperties.MUSIC_DIR, track + ".mp3");
			return null;
		}
		 
		@Override
		protected void onPostExecute(Void result)
		{
			Log.d(TAG, "onPostExecute");
			setContentView(R.layout.songview);
			
			TextView titleTv = (TextView)findViewById(R.id.title);			
			titleTv.setText(Html.fromHtml(titleTv.getText() + "  " + "<b>" +  title+ "</b>"));
			
			TextView authorTv = (TextView) findViewById(R.id.author);
			authorTv.setText(Html.fromHtml(authorTv.getText() + "  " + "<b>" + author + "</b>"));
			
			TextView releaseTv = (TextView) findViewById(R.id.release);
			releaseTv.setText(Html.fromHtml(releaseTv.getText() + " " + "<b>" + releasedate + "</b>"));
			
			TextView downloadTv = (TextView) findViewById(R.id.download);
			downloadTv.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mp.stop();
					Intent wvIntent = new Intent(SongActivity.this, WebViewActivity.class);
					wvIntent.putExtra("weblink", download);
					startActivity(wvIntent);					
				}
			});
			
			locandinaBtn = (ImageView) findViewById(R.id.buttonCover);		
			 if(image!=null)locandinaBtn.setImageDrawable(image);

			 TextView tvTicker = (TextView) findViewById(R.id.titleTicker);  
			 tvTicker.setEllipsize(TruncateAt.MARQUEE);

			 tvTicker.setText("You are listening to " + title + " by " + author);
			 tvTicker.setSelected(true);
			 
			 Button buttonPlay = (Button)findViewById(R.id.btnPlay);
			 buttonPlay.setOnClickListener(new OnClickListener() {				

				public void onClick(View v) {
					if(!mp.isPlaying()){
						try {
							mp.prepareAsync();
						} catch (IllegalStateException e) {
							e.printStackTrace();
						}
						mp.start();					
					}
				}
			});
		
//			 Button buttonStop = (Button) findViewById(R.id.btnStop);
//			 buttonStop.setOnClickListener(new OnClickListener() {
//				
//		
//				public void onClick(View v) {
//					// TODO Auto-generated method stub
//					if(mp.isPlaying() || mp.isLooping()){
//						mp.reset();
//					}
//				}
//			});
			
			Button buttonPause = (Button) findViewById(R.id.btnPause);
			buttonPause.setOnClickListener(new OnClickListener() {
				
		
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(mp.isPlaying()){
						mp.pause();
					}
				}
			});
			
			myProgressDialog.dismiss();
		}
	 }
	 	 

	public void onBackPressed() {
		// TODO Auto-generated method stub
		mp.release();	
		finish();	 
	}
	 
}
